/*************************************************************************
	> File Name: client_discover.c
	> Author: Maureen 
	> Mail: 1437867946@qq.com 
	> Created Time: Wed 13 Jan 2021 04:32:44 PM CST
 ************************************************************************/

#include "head.h"

extern char *conf; 
extern char name[20];
extern char msg[512];
//给iplist中的所有用户发送SYN报文
void *client_discover(void *arg) {
    //读取.iplist文件
    char file[512] = {0};
    FILE *fp;
    struct Msg request;
    struct sockaddr_in client;
    int sockfd = *((int *)arg);
    DBG(GREEN"sockfd = %d\n", sockfd);
    /*if ((sockfd = socket_udp()) < 0) {//随机端口
        perror("socket_udp");
        exit(1);
    }*/
    strcpy(request.from, name);
    strcpy(request.msg, msg);
    request.type = CHAT_SYN;
    strcpy(file, get_value(conf, "iplist"));
    if ((fp = fopen(file, "r")) == NULL) {
        perror("fopen");
        exit(1); //进程会退出
    }
    //循环读取ip地址并打印
    DBG("[client_discover]<IP Discover> Start to send msg to peers...\n");
    
    client.sin_family = AF_INET;
    client.sin_port = htons(8888);
    while (!feof(fp)) {
        char ip[20] = {0};
        fscanf(fp, "%s", ip);
        if (!strlen(ip)) continue;
        client.sin_addr.s_addr = inet_addr(ip);
        sendto(sockfd, (void *)&request, sizeof(request), 0, (struct sockaddr *)&client, sizeof(client));

        //DBG("<IP Discover> %s\n", ip);
    }
    DBG("[client_discover]<IP Discover> End to send msg to every peer!\n");
}
